package com.yyi.springcloud.controller;


import com.yyi.springcloud.service.UserService;
import com.yyi.springcloud.utils.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/api/user")
public class Mysql_UserController {
    @Resource
    private UserService userService;

    // http://localhost:8080/bxxs/api/user/user
    @ResponseBody
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String User(HttpServletRequest request, Model model, HttpServletResponse response) {
        System.out.println(userService.selectUserByUserName("demo"));
        HttpSession session = request.getSession();
        //使用spring-session将session整合到redis中
        session.setAttribute("sxl","demo");
        return userService.selectUserByUserName("show").getUserPwd();
    }
    // http://localhost:8080/bxxs/api/user/alluser
    @ResponseBody
    @RequestMapping(value = "/alluser", method = RequestMethod.GET)
    public String AllUser(HttpServletRequest request, Model model, HttpServletResponse response) {
        return JsonUtil.list2json(userService.selectAllUser());
    }
    //测试使用Springmvc保存cookie
    // http://localhost:8080/bxxs/api/user/SaveCookie
    @ResponseBody
    @RequestMapping(value = "/SaveCookie", method = RequestMethod.GET)
    public String SaveCookie(HttpServletRequest request, Model model, HttpServletResponse response) {
        Cookie nameCookie = new Cookie("TestCookie", "sxl");
        //注意:Windows10 SpringMVC中需要使用setPath()才能保证cookie保存成功
        nameCookie.setPath("/");
        nameCookie.setMaxAge(7 * 24 * 60 * 60);
        response.addCookie(nameCookie);
        return "success";
    }

}
